#!/bin/sh
#export JAVA_HOME=/opt/app/jdk1.8.0_152
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar
export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

#模糊查询最新打包的jar文件名
APP_NAME=`ls -lt  *.jar | head -n 1 |awk '{print $9}'`
echo -e "The current app name is：\033[35m$APP_NAME\033[0m"

#检查程序是否在运i行

is_exist(){
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'`
port=`netstat -tunlp | grep " $pid/"|awk '{print $4}'|awk -F '[:]' '{print $NF}' | awk '{a=a$1"  "}END{print a}'` 
 #如果不存在返回1，存在返回0     
  #if [ -z "${pid}" ]; then
  if [ -z "${pid}" -o -z "${port}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid is ${pid}, port is ${port}"
  else
    nohup ${JAVA_HOME}/bin/java -jar -Xms64m -Xmx256m -Xmn64m -XX:MaxMetaspaceSize=256m ${APP_NAME} --spring.profiles.active=test >/dev/null 2>nohup.out &
    echo "${APP_NAME} is starting"
    while true; do
      is_exist
      if [ $? -eq 0 ]; then
	  echo -e  "\n${APP_NAME} is start completed. pid is ${pid}, port is ${port}"
	  break;
      else
	  echo -e ".\c"
	  sleep 0.02
      fi
    done 
  fi
}

#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -15 $pid
    echo "${APP_NAME} is closing. pid is $pid, port is $port"
    while true; do
      is_exist
      if [ $? -eq "1" ]; then
	 echo -e "\n${APP_NAME} is shutdown"
         break;
      else
	 echo -e ".\c"
	 sleep 0.02
      fi
    done      
  else
    echo "${APP_NAME} is not running"
  fi  
}
 
#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. pid is ${pid}, port is ${port}"
  else
    echo "${APP_NAME} is not running."
  fi
}
 
#重启
restart(){
  stop
  sleep 1
  start
}

#使用说明
usage(){
  echo -e "参数输入错误:\033[31m$1\033[0m , 支持以下参数："
  echo -e "\033[36mstart\033[0m\t:启动程序"
  echo -e "\033[36mstop\033[0m\t:停止程序"
  echo -e "\033[36mrestart\033[0m\t:重启程序"
  echo -e "\033[36mstatus\033[0m\t:查看程序运行状态"
}

case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage $1
    ;;
esac
